import React, { useState } from 'react';
import { Select, message, Spin, Button, Form, Table, Input } from 'antd';
import { useSetState } from 'ahooks';
import _ from 'lodash';
import { connect } from 'umi';
import { tableLocale } from '@/tool/components/PageEmpty';
import { TRAlert, TRDefault, TRCheckboxModal } from '#/components/index.js';
import { PlusCircleOutlined, DownOutlined, MinusCircleOutlined } from '#/utils/antdIcons.js';
import { HttpCode } from '#/utils/contacts.js';
import { SelectAll } from './components/index';
import {
  postQueryNodeList,
  postQueryNodeStationList,
  postSaveNodeStation,
  queryMarketList,
} from './service';
import type {
  IProps,
  IOptionType,
  IOrginDealElementOptions,
  INodeListType,
  INodeStationListType,
  IStationsData,
  IStationListType,
  IParamsDataType,
} from './type';
import { INodeStationConfigPermissions } from './type';
import { havePermissions, getDealElementOptions } from './tool';
import styles from './index.less';
// @ts-ignore
import { getTreeByCodes } from '@/utils';

const NodeStationConfig = (props: IProps) => {
  const { menuCode, buttonPermissions } = props;
  const [form] = Form.useForm();
  const [loading, setLoading] = useState<boolean>(true);
  const [isLoding, setIsLoding] = useState<boolean>(false);
  const [isError, setIsError] = useState<boolean>(false);
  const [listLoading, setListLoading] = useState<boolean>(false);
  const [isListError, setIsListError] = useState<boolean>(false);
  const [provinceOptions, setProvinceOptions] = useState<IOrginDealElementOptions[]>([]); // 省份数据
  const [marketId, setMarketId] = useState<string>(menuCode); // 交易中心id]
  const [checkedProvinceId, setCheckedProvinceId] = useState<string>(); // 选中的省份id
  const [oriNodeStationList, setOriNodeStationList] = useState<INodeStationListType[]>([]);
  const [nodeStationList, setNodeStationList] = useState<INodeStationListType[]>([]); // 配置列表
  const [stationData, setStationData] = useSetState<IStationsData>({
    dealElementOptions: [],
    dealElementModalOptions: [],
    originDealElementOptions: [],
    dealElementDataObj: {},
  }); // 交易单元列表
  const [nodeOptionList, setNodeOptionList] = useState<IOptionType[]>([]); // 节点列表

  const onBeforeunload = async (e: any) => {
    const tableForm: INodeStationListType[] = (form && form.getFieldValue('tableForm')) || [];
    const _oriNodeStationList: INodeStationListType[] =
      (form && form.getFieldValue('oriNodeStationList')) || [];
    const params = tableForm.map((item: INodeStationListType) => {
      const { stationIdList = [], stationList, ...rest } = item || {};
      return {
        ...rest,
        stationList: stationList,
      };
    });
    const isSame = _.isEqual(params, _oriNodeStationList);
    if (!isSame) {
      const confirmationMessage = '当前工作将不被保存，继续执行此操作？';
      (e || window.event).returnValue = confirmationMessage;
      return confirmationMessage;
    }
  };

  const { dealElementDataObj, dealElementModalOptions, dealElementOptions } = stationData;

  // 获取节点
  const getNodeList = async (provinceId: string) => {
    const res = await postQueryNodeList({
      provinceId,
    });
    if (res && res.statusCode === HttpCode.SUCCESS) {
      const _nodeOptionList = (res.data || []).map((item: INodeListType) => ({
        label: item?.nodeName,
        value: item?.nodeId,
      }));
      setNodeOptionList(_nodeOptionList);
    } else {
      message.error(res?.message || '系统异常');
    }
  };

  // 获取配置列表
  const getNodeStationList = async (provinceId: string) => {
    setListLoading(true);
    setIsListError(false);
    const res = await postQueryNodeStationList({
      provinceId,
    });
    if (res && res.statusCode === HttpCode.SUCCESS) {
      const _tableForm = (res?.data || []).map((item: INodeStationListType) => {
        const { stationList = [], ...rest } = item || {};
        const _stationIdList = stationList?.map((i: IStationListType) => {
          return i.stationId;
        });
        return {
          ...rest,
          stationList,
          stationIdList: _stationIdList,
        };
      });
      form &&
        form.setFieldsValue({
          tableForm: [...(_tableForm || [])],
          oriNodeStationList: res?.data || [],
        });
      setNodeStationList(_tableForm || []);
      setOriNodeStationList(res?.data || []);
    } else {
      setIsListError(true);
      message.error(res?.message || '系统异常');
    }
    setListLoading(false);
  };

  // 获取交易单元数据
  const getStationList = (data: IOrginDealElementOptions[]) => {
    const _dealElementResultData = getDealElementOptions(data || []);
    setStationData({
      dealElementOptions: _dealElementResultData?.value || [],
      // @ts-ignore
      dealElementModalOptions: _dealElementResultData?.modalData || [],
      dealElementDataObj: _dealElementResultData.dataObj,
    });
  };

  // 改变省份
  const onChangeProvince = (e: string, opt: any) => {
    form &&
      form.validateFields().then(async (valus) => {
        const _stationList = provinceOptions.find((item: IOrginDealElementOptions) => {
          return item.marketId === e;
        })?.children;
        const { tableForm = [] } = valus || {};
        const params = tableForm.map((item: INodeStationListType) => {
          const { stationIdList = [], stationList, ...rest } = item || {};
          return {
            ...rest,
            stationList: stationIdList?.map((i: string) => ({
              stationId: i,
              // @ts-ignore
              stationName: dealElementDataObj[i]?.[0]?.label,
            })),
          };
        });
        const isSame = _.isEqual(params, oriNodeStationList);
        if (isSame) {
          getNodeList(opt.provinceId);
          getNodeStationList(opt.provinceId);
          setCheckedProvinceId(opt.provinceId);
          setMarketId(e);
          getStationList(_stationList || []);
        } else {
          const result = await TRAlert.show('当前工作将不被保存，继续执行此操作？');
          if (result.index === 1) {
            getNodeList(opt.provinceId);
            getNodeStationList(opt.provinceId);
            setCheckedProvinceId(opt.provinceId);
            getStationList(_stationList || []);
            setMarketId(e);
          }
        }
      });
  };

  const filterOption = (input: string, option: { value: any; label: any }) => {
    return option?.label?.toLowerCase().indexOf(input.toLowerCase()) >= 0;
  };

  // 添加
  const onAdd = () => {
    form &&
      form.validateFields().then(() => {
        let _tableForm = (form && form.getFieldValue('tableForm')) || [];
        const _provinceId = checkedProvinceId;
        const _provinceName = provinceOptions.find((i) => i.value === checkedProvinceId)?.label;
        _tableForm = [..._tableForm, { provinceId: _provinceId, provinceName: _provinceName }];
        form &&
          form.setFieldsValue({
            tableForm: [..._tableForm],
          });
        setNodeStationList([..._tableForm]);
      });
  };

  // 保存节点
  const onSave = async () => {
    const resoult = havePermissions(
      INodeStationConfigPermissions.NODESTATIONCONFIGSAVEBUTTONWEB,
      buttonPermissions,
    );
    if (resoult) {
      form &&
        form.validateFields().then(async (valus) => {
          const { tableForm = [] } = valus || {};
          const _data: IParamsDataType[] = tableForm.map(
            (item: INodeStationListType, index: number) => {
              const { stationIdList = [], stationList, ...rest } = item || {};
              return {
                ...rest,
                rank: index + 1,
                stationList: stationIdList?.map((i: string) => ({
                  stationId: i,
                  // @ts-ignore
                  stationName: dealElementDataObj[i]?.[0]?.label,
                })),
              };
            },
          );
          const params = {
            data: _data,
            provinceId: checkedProvinceId || '',
          };
          setIsLoding(true);
          const res = await postSaveNodeStation(params);
          if (res && res.statusCode === HttpCode.SUCCESS) {
            message.info('保存成功');
            checkedProvinceId && getNodeStationList(checkedProvinceId);
          } else {
            message.info(res?.message || '保存失败');
          }
          setIsLoding(false);
        });
    }
  };

  // 改变节点
  const onChangeNodeId = (e: any, index: number) => {
    const _tableForm = _.cloneDeep((form && form.getFieldValue('tableForm')) || []);
    let _obj = _tableForm[index] || {};
    const isExist = nodeStationList.find(
      (item: INodeStationListType, j: number) => index !== j && item?.nodeId && item?.nodeId === e,
    );
    if (isExist) {
      message.error('节点不允许重复选择!');
      _obj = {
        ..._obj,
        nodeId: null,
        nodeName: '',
      };
    } else {
      _obj = {
        ..._obj,
        nodeId: e,
        nodeName: nodeOptionList.find((item) => item.value === e)?.label,
      };
    }
    const _arr = _tableForm.map((item: any, j: number) => {
      if (j === index) {
        return _obj;
      } else {
        return item;
      }
    });
    // _tableForm.splice(index, 1, _obj);
    form &&
      form.setFieldsValue({
        tableForm: _arr,
      });
    setNodeStationList([..._arr]);
  };

  // 改变展示名称
  const onChangeNodeNameAlias = (e: any, index: number) => {
    const _nodeNameAlias = e.target.value;
    const _tableForm = _.cloneDeep((form && form.getFieldValue('tableForm')) || []);
    let _obj = _tableForm[index] || {};
    const isExist = nodeStationList.find(
      (item: INodeStationListType, j: number) =>
        index !== j && item?.nodeNameAlias && item?.nodeNameAlias === _nodeNameAlias,
    );
    if (isExist) {
      message.error('展示名称不允许重复!');
      _obj = {
        ..._obj,
        nodeNameAlias: '',
      };
    } else {
      _obj = {
        ..._obj,
        nodeNameAlias: _nodeNameAlias,
      };
    }
    _tableForm.splice(index, 1, _obj);
    form &&
      form.setFieldsValue({
        tableForm: _tableForm,
      });
    setNodeStationList([..._tableForm]);
  };

  // 点击交易单元弹出Modal框
  const handelSelectDealElement = async (index: number) => {
    const _tableForm = _.cloneDeep((form && form.getFieldValue('tableForm')) || []);
    let _obj = _tableForm[index] || {};
    let checkedKeys: string[] = [];
    const data = _tableForm[index]?.stationIdList || [];
    const _allStationIdList: string[] = [];
    _tableForm?.forEach((item: INodeStationListType, j: number) => {
      if (index !== j) {
        _allStationIdList.push(...(item?.stationIdList || []));
      }
    });
    const result = await TRCheckboxModal.show({
      treeData: dealElementModalOptions,
      value: data,
      title: '交易单元',
    });
    if (result.index === 1) {
      const _data: string[] = [];
      const _checkedKeys = result?.checkedKeys;
      const _existStationNameList: string[] = [];
      _checkedKeys.forEach((item: string) => {
        const _stationId = _allStationIdList.find((i: string) => i === item);
        if (_stationId) {
          // @ts-ignore
          const stationName: string = dealElementDataObj?.[_stationId]?.[0]?.label || '';
          stationName && _existStationNameList.push(stationName);
        } else {
          _data.push(item);
        }
      });
      if (_existStationNameList?.length > 0) {
        message.error(`以下交易单元关联多个节点：${_existStationNameList.join(',')}`);
      }
      checkedKeys = _data;
    } else {
      checkedKeys = data;
    }
    const _stationList = checkedKeys.map((item: string) => {
      // @ts-ignore
      const _stationName: string = dealElementDataObj?.[item]?.[0]?.label || '';
      return {
        stationId: item,
        stationName: _stationName,
      };
    });
    _obj = {
      ..._obj,
      stationList: _stationList,
      stationIdList: checkedKeys,
    };
    _tableForm.splice(index, 1, _obj);
    form.setFieldsValue({
      tableForm: _tableForm,
    });
    return checkedKeys;
  };

  // 获取省份列表
  const getProvinceData = async () => {
    setLoading(true);
    const res = await queryMarketList(menuCode);
    if (res && res.statusCode === HttpCode.SUCCESS) {
      const power = getTreeByCodes(['market', 'group', 'station'], res.json).treeOptions;
      setProvinceOptions(power || []);
      setCheckedProvinceId(power?.[0]?.provinceId);
      setMarketId(power?.[0]?.marketId);
      getNodeList(power?.[0]?.provinceId);
      getNodeStationList(power?.[0]?.provinceId);
      getStationList(power?.[0]?.children || []);
    } else {
      setIsError(true);
    }
    setLoading(false);
  };

  React.useEffect(() => {
    getProvinceData();
  }, []);

  React.useEffect(() => {
    window.addEventListener('beforeunload', onBeforeunload);
    return () => {
      window.removeEventListener('beforeunload', onBeforeunload);
    };
  }, []);

  const getColumns = (remove: any) => {
    return [
      {
        title: '序号',
        dataIndex: 'rank',
        width: 60,
        render(text: number, field: any, index: number) {
          return <div className={styles.logo}>{index + 1 ?? '-'}</div>;
        },
      },
      {
        title: '节点',
        dataIndex: 'nodeId',
        width: 290,
        render(text: string, field: any, index: number) {
          return (
            <Form.Item
              rules={[{ required: true, message: '请选择节点' }]}
              name={[field.name, 'nodeId']}
              fieldKey={[field.fieldKey, 'nodeId']}
            >
              <Select
                placeholder={'节点'}
                showArrow={true}
                options={nodeOptionList as any[]}
                showSearch={true}
                onChange={(e) => onChangeNodeId(e, index)}
                filterOption={filterOption as any}
              />
            </Form.Item>
          );
        },
      },
      {
        title: '展示名称',
        dataIndex: 'nodeNameAlias',
        width: 290,
        render(text: string, field: any, index: number) {
          return (
            <Form.Item
              rules={[
                { required: true, message: '请输入展示名称' },
                {
                  pattern: /^[^\s]*$/,
                  message: '禁止输入空格',
                },
                {
                  max: 10,
                  message: '展示名称最大长度为10个字符',
                },
              ]}
              name={[field.name, 'nodeNameAlias']}
              fieldKey={[field.fieldKey, 'nodeNameAlias']}
            >
              <Input
                placeholder="请输入展示名称"
                maxLength={10}
                onBlur={(e) => onChangeNodeNameAlias(e, index)}
                autoComplete="off"
              />
            </Form.Item>
          );
        },
      },
      {
        title: '交易单元',
        dataIndex: 'stationIdList',
        render(text: string, field: any, index: number) {
          return (
            <Form.Item
              name={[field.name, 'stationIdList']}
              fieldKey={[field.fieldKey, 'stationIdList']}
            >
              <SelectAll
                placeholder="请选择"
                alltitle="全部交易单元"
                logo={<DownOutlined />}
                showArrow={true}
                open={false}
                maxTagCount={4}
                style={{ minWidth: 200 }}
                maxTagTextLength={10}
                onClick={() => handelSelectDealElement(index)}
                options={(dealElementOptions || []) as any}
              />
            </Form.Item>
          );
        },
      },
      {
        title: '',
        dataIndex: 'operate',
        className: 'operate',
        align: 'center',
        width: 60,
        render(text: string, field: any) {
          return (
            <div className={styles.logo}>
              <MinusCircleOutlined
                onClick={() => {
                  remove(field.name);
                  const _tableForm = form && form.getFieldValue('tableForm');
                  setNodeStationList(_tableForm);
                }}
              />
            </div>
          );
        },
      },
    ];
  };

  return (
    <Spin spinning={loading}>
      {loading ? (
        <div className={styles.container} />
      ) : isError ? (
        <TRDefault type={'error'} message={'系统异常'} />
      ) : (
        <div className={styles.container}>
          <div className={styles.header}>
            <Select
              className={styles.select}
              placeholder={'请选择省份'}
              showArrow={true}
              key="value"
              value={marketId}
              options={provinceOptions as any[]}
              showSearch={true}
              filterOption={filterOption as any}
              onChange={onChangeProvince}
            />
          </div>
          <div className={styles.main}>
            <div className={styles.content}>
              {listLoading ? (
                <Spin spinning={listLoading} />
              ) : (
                <div className={styles.stationConfig}>
                  <div className={styles.head}>
                    <div className={styles.title}>节点及交易单元配置</div>
                    {isListError ? null : (
                      <Button
                        type="primary"
                        onClick={onSave}
                        loading={isLoding}
                        className={styles.button}
                      >
                        保存
                      </Button>
                    )}
                  </div>
                  {isError ? (
                    <TRDefault type={'error'} message={'系统异常'} />
                  ) : nodeStationList.length > 0 ? (
                    <div className={styles.center}>
                      <Form
                        className={styles.form}
                        form={form}
                        initialValues={{
                          tableForm: [{}],
                        }}
                      >
                        <Form.List name="tableForm">
                          {(fields, { remove }) => {
                            return (
                              <Table
                                dataSource={fields}
                                locale={tableLocale}
                                columns={getColumns(remove) as any}
                                rowKey="key"
                                bordered={false}
                                pagination={false}
                                scroll={{ y: 'calc(100vh - 270px)' }}
                              />
                            );
                          }}
                        </Form.List>
                      </Form>
                    </div>
                  ) : null}
                  {isListError ? null : (
                    <div className={styles.bottom}>
                      <div className={styles.button} onClick={onAdd}>
                        <div className={styles.logo}>
                          <PlusCircleOutlined className={styles.icon} />
                        </div>
                        <div className={styles.text}>添加</div>
                      </div>
                    </div>
                  )}
                </div>
              )}
            </div>
          </div>
        </div>
      )}
    </Spin>
  );
};

export default connect(
  ({ nodeStationConfig, global }: { nodeStationConfig: any; global: any }) => ({
    global,
    menuCode: global.configure.menuCode,
    buttonPermissions: global.configure.buttonPermissions,
    nodeStationConfig,
  }),
)(NodeStationConfig);
